#include "login.h"

int littleLogin(const char *key,const char *usrname,char * uname){
    //printf("usrname=%s,key=%s\n",usrname,key);
    char *name = (char*)calloc(strlen(usrname)+1,sizeof(char));
    strncpy(name,usrname,strlen(usrname));
    //printf("name=%s\n",name);
    struct spwd *pspwd = getspnam(name);//如果用户名错误会直接
    if(pspwd == NULL){
        printf("用户名或密码错误！\n");
        return -1;
    }
    printf("name=%s\n",name);
    //printf("pspwd.key=%s",pspwd->sp_pwdp);
    //获取该用户名的密文密码
    char *encrypted_password = (char*)calloc(1024,sizeof(char));
    strncpy(encrypted_password,pspwd->sp_pwdp,strlen(pspwd->sp_pwdp));
    printf("encrypted_password=%s\n",encrypted_password);
    //获取该用户的盐值
    char *salt = (char*)calloc(1024,sizeof(char));
    int length = strlen(pspwd->sp_pwdp);
    int i = length - 1;
    while(encrypted_password[i] != '$'){
        i--;
    }
    strncpy(salt,encrypted_password,i+1);
    printf("salt=%s\n",salt);
    
    char encrypted_key[1024] = {0};
    strncpy(encrypted_key,crypt(key,salt),strlen(crypt(key,salt)));
    if(strncmp(encrypted_key,encrypted_password,length) != 0){
        printf("用户名或密码错误！\n");
        return -1;
    }
    printf("登录成功!\n");
    strncpy(uname,name,strlen(name));
    free(name);
    free(salt);
    free(encrypted_password);
    return 0;
}




char * login()
{
    char key[1024] = {0};
    char usrname[1024] = {0};
    int ret = 1;
    char * name = (char *)calloc(1024,sizeof(char));
    while(ret != 0){
        printf("请输入用户名\n");
        scanf("%s",usrname);
        printf("请输入密码\n");
        scanf("%s",key);

        ret = littleLogin(key,usrname,name);
    }
    return name;
}
